package miku.firstgame.model.proxy
{
	import miku.firstgame.constrants.AppConstrants;
	import miku.firstgame.constrants.ProtocalConstants;
	import miku.firstgame.model.Me;
	import miku.firstgame.model.Room;
	import miku.firstgame.model.User;
	import miku.firstgame.net.IConnection;
	import miku.firstgame.net.pack.UserOfflineResponsePack;
	import miku.firstgame.net.pack.UserOnlineResponsePack;
	import miku.firstgame.net.proxy.Connection;
	
	import org.puremvc.as3.patterns.proxy.Proxy;

	public class LobbyProxy extends Proxy
	{
		public static const NAME:String = "LobbyProxy";

		//TODO 需要添加offline user 保存所有离线用户集合 
		//出于性能考虑，看是不是需要加上一个dic
		private var users:Vector.<User>;

		public function LobbyProxy()
		{
			super(NAME);
			users = new Vector.<User>();
		}

		override public function onRegister():void
		{
			super.onRegister();
			
			Connection.getInstance().registerProtocolInterest(handleOnline, [ProtocalConstants.USER_ONLINE]);
			Connection.getInstance().registerProtocolInterest(handleOffline,  [ProtocalConstants.USER_OFFLINE]); //"uxr"用户退出房间
		}

		override public function onRemove():void
		{
			super.onRemove();
			Connection.getInstance().unregisterHandler(handleOffline);
			Connection.getInstance().unregisterHandler(handleOnline);
		}

		/**
		 * 在大厅，房间，游戏中都需要考虑
		 * */
		private function handleOffline(pack:UserOfflineResponsePack, connection:IConnection):void
		{
			var user:User = removeUser(pack.userId);
			if (user)
			{
				sendNotification(AppConstrants.USER_OFFLINE, user);
			}
		}

		/**
		 * <ol n="User2" id="2"/>
		 * */
		private function handleOnline(pack:UserOnlineResponsePack, connection:IConnection):void
		{
			var newUser:User = pack.user;
			addUser(newUser);
			sendNotification(AppConstrants.USER_ONLINE, newUser);
		}

		public function removeUser(id:int):User
		{
			var user:User = getUser(id);
			if (user)
			{
				var index:int = users.indexOf(user);
				users.splice(index, 1);
				return user;
			}
			return null;
		}

		public function addUser(user:User):void
		{
			users.push(user);
		}

		public function getUser(id:int):User
		{
			for each (var user:User in users)
			{
				if (user.id == id)
				{
					return user;
				}
			}
			return null;
		}

		public function getAllUser():Vector.<User>
		{
			return users;
		}

		public function clearAllUsers():void
		{
			users = new Vector.<User>();
		}

		public function setUsers(users:Vector.<User>):void
		{
			this.users = users;
		}

	}
}
